package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R save(@RequestBody Category category){
    //添加
        categoryService.save(category);
        return R.success();
    }

    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(required = false,defaultValue = "1") int page,
                                  @RequestParam(required = false,defaultValue = "10")int pageSaze){
        //分页参数
        Page<Category> pageInfo = new Page<>(page,pageSaze);
        //查询及排序条件
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(Category::getSort);

        //执行分页查询
        categoryService.page(pageInfo,lambdaQueryWrapper);

        //返回结果
        return R.success(pageInfo);
    }

    @DeleteMapping("/{id}")
    public  R delete(@PathVariable Long id){

        categoryService.remove(id);
        return R.success();
    }

    @GetMapping("/{id}")
    public R<Category> getById(@PathVariable Long id ){

        Category category = categoryService.getById(id);

        if (category!=null){
            return R.success(category);
        }
        return R.error("该分类数据不存在");
    }

    @PutMapping
    public R  update(@RequestBody Category category){

        categoryService.updateById(category);
        return R.success();
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //组装查询条件
        LambdaQueryWrapper <Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //执行查询
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        //返回结果
        return R.success(list);
    }
}
